package com.ns.attendance.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {
	private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
	public static final String GET = "get";
	public static final String POST = "post";
	
	private static final int CONNECTION_TIMEOUT = 10000;
	
	private static HttpClient client = HttpClients.createDefault();
	
	
	public static String excuteGet(String url,Map<String,String> map){
		RequestConfig config = RequestConfig.custom()
							  .setSocketTimeout(CONNECTION_TIMEOUT)
							  .setConnectTimeout(CONNECTION_TIMEOUT)
							  .build();
		
		url += "?";
		for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();it.hasNext();){
			Map.Entry<String, String> entry = it.next();
			if(entry.getValue() != null){
				url+=(entry.getKey()+"="+entry.getValue());
			}
			if(it.hasNext()){
				url+="&";
			}
		}
		log.info(url);
		HttpGet get = new HttpGet(url);
		get.setConfig(config);
		try {
			HttpResponse response = client.execute(get);
			return EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static String excutePost(String url,Map<String,String> map){
		RequestConfig config = RequestConfig.custom()
							  .setSocketTimeout(CONNECTION_TIMEOUT)
							  .setConnectTimeout(CONNECTION_TIMEOUT)
							  .build();
		HttpPost post = new HttpPost(url);
		post.setConfig(config);
		try {
			post.setEntity(new UrlEncodedFormEntity(buildParams(map),"UTF-8"));
			HttpResponse response = client.execute(post);
			return EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	static List buildParams(Map params){
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		Iterator it=params.keySet().iterator();
		while(it.hasNext()){
			String key=(String)it.next();
			String v=(String)params.get(key);
			nvps.add(new BasicNameValuePair(key, v));
		}
		return nvps;
	}
	
}
